package com.learn.handler;

import com.learn.context.GetBeanUtil;
import com.learn.pojo.RpcRequest;
import com.learn.service.IUserService;
import com.learn.service.UserServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @program: rmi
 * @description
 * @author: luffy
 * @create: 2020-08-17 13:50
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter {
    /**
     * 当客户端读取数据时候，该方法会被调用
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {


        //注意：客户端将来会发送一个秦秋的时候回传递一个参数：UserService#sayHello#are you ok
        //1.判断当前的请求是否符合规则
//        if (msg.toString().startsWith("UserService")) {
//            //2.符合规则，调用实现类获得一个result
//            UserServiceImpl userService = new UserServiceImpl();
//            msg = msg.toString().substring(msg.toString().lastIndexOf("#") + 1);
//            String result = userService.sayHello(msg.toString());
//            //3.把调实现类的方法获得的结果写到客户端
//            ctx.writeAndFlush("服务器返回的数据"+result);
//        }


        if (msg != null) {
            RpcRequest request = (RpcRequest) msg;
            if (request.getRequestId().equals("IUserService")) {
                Class<?> clazz = Class.forName(request.getClassName());
                Method declaredMethod = clazz.getDeclaredMethod(request.getMethodName(), request.getParameterTypes());
                Object bean = GetBeanUtil.getBean(request.getRequestId());
                Object invoke = declaredMethod.invoke(bean, request.getParameters());
                ctx.writeAndFlush("服务器返回：success");
            }

        }








    }
}
